import { getUserInfo, login, register } from '@a/index.js'
import { routes } from '@r/index.js'
import { setToken } from '@u/auth.js'
import { defineStore } from 'pinia'

const hasPermission = (role, route) => {
  if (route.meta && route.meta.roles) {
    return route.meta.roles.includes(role)
  } else {
    return true
  }
}

const filterAsyncRoutes = (routers, role) => {
  const res = []

  routers.forEach(route => {
    const tmp = { ...route }
    if (hasPermission(role, tmp)) {
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, role)
      }
      res.push(tmp)
    }
  })

  return res
}

// Create a new store instance.
const useUserStore = defineStore('user', {
  // other options...
  state: () => {
    return {
      userInfo: {},
      routes: [],
    }
  },
  actions: {
    async handleLogin(params) {
      const data = await login(params)
      setToken(data.data.token)
      return data.data
    },
    async handleRegister(params) {
      const data = await register(params)
      return data.data
    },
    async _getUserInfo(token) {
      const userInfo = await getUserInfo(token)
      this.userInfo = userInfo.data
      return userInfo.data
    },
    async generateRoutes(role) {
      return new Promise((resolve, reject) => {
        let accessedRoutes = []
        if (role === 'superAdmin') {
          accessedRoutes = routes || []
        } else {
          accessedRoutes = filterAsyncRoutes(routes, role)
        }
        this.routes = accessedRoutes
        resolve(accessedRoutes)
      })
    },
  },
  getters: {},
  // 是否开启数据持久化
  persist: false,
})

export default useUserStore
